/**
 * Copyright 2016-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.inmorn.extspring.context;

import java.util.Properties;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.inmorn.extspring.util.StringUtils;

/**
 * 获取spring bean对象
 * @author Jeff.Li
 *
 */
@Component
public class BeanHolder implements ApplicationContextAware{
	
	private static ApplicationContext application = null;
	
	/**
	 * 根据Bean id和Bean对应Class获取Spring上下文Bean实例
	 * @param id
	 * @param clazz
	 * @return
	 */
	public static <T> T getBean(String id,Class<T> clazz){
		return application.getBean(id,clazz);
	}
	
	/**
	 * 根据Bean id获取Spring上下文Bean实例
	 * @param id
	 * @param clazz
	 * @return
	 */
	public static Object getBean(String id){
		return application.getBean(id);
	}
	
	/**
	 * 根据Bean对应Class获取Spring上下文Bean实例
	 * @param id
	 * @param clazz
	 * @return
	 */
	public static <T> T getBean(Class<T> clazz){
		String beanName = StringUtils.firstToLowerCase(clazz.getSimpleName());
		return getBean(beanName,clazz);
	}
	
	/**
	 * 根据属性Key获取application.properties以及YTPBL.T_PBL_PROPERTIES表中的值
	 * @param key
	 * @return
	 */
	public static String getProperty(String key){
		String value = null;
		Properties properties = getBean("configProperties", Properties.class);
		if(properties != null){
			value = properties.getProperty(key, null);
		}
		return value;
	}

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		if(application == null){
			application = applicationContext;
		}
	}
}
